import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCollection;
import devboard.dbutil.MongoUtil;

@WebFilter("/UserLogged")
public class UserLogged implements Filter {
	String s=null;
	public UserLogged() {
    	
    }
    
	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse resp=(HttpServletResponse)response;
		if((req.getSession().getAttribute("_id")!=null)||(req.getRequestURI().indexOf("Registration.jsp")>-1) ){
				if(req.getParameter("logout")!=null&&req.getParameter("logout").equals("true")){
				req.getSession().invalidate();
				chain.doFilter(req, resp);
				return;				
			}
			chain.doFilter(req, resp);
			return;
		}else if(req.getParameter("email")!=null&&req.getParameter("password")!=null){
				DBCollection users=MongoUtil.getCollection("Users");
				DBObject obj;
				
				if((obj=users.findOne(new BasicDBObject("_id",req.getParameter("email"))))!=null){
					
					if(obj.get("_id").equals(req.getParameter("email"))&&obj.get("password").equals(req.getParameter("password"))){
						req.getSession().setAttribute("_id", req.getParameter("email"));
						req.getSession().setAttribute("firstName", obj.get("firstName"));
						req.getSession().setAttribute("lastName", obj.get("lastName"));
						chain.doFilter(req, resp);
						return;
					}else{
						resp.sendRedirect("Login.jsp?logFail=true");
					return;
					}
					
				}
				resp.sendRedirect("Login.jsp?logFail=true");
				return;
			}
		RequestDispatcher rd=req.getRequestDispatcher("Login.jsp");
		rd.forward(req, resp);
	}
	
	public void loginRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		resp.sendRedirect("Login.jsp");
		}

	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
